package com.ruoyi.quartz.task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.CmdResult;
import com.ruoyi.common.utils.BashUtils;
import com.ruoyi.common.utils.StringUtils;

/**
 * 设备相关任务执行实现
 * 
 * @author ruoyi
 */
public class SaltFn {
	private static final String AFTER_CMD_ASYN = "  --asyn";

	private static final String AFTER_CMD_JSON = "  --out=json";

	private static final String BEFORE_CMD_STR = " echo '123' | sudo -S echo '123' > /dev/null  ; ";

	public static final String DOCKER_ERROR_MESSAGE = "Error response from daemon";

	public static String execCommand(String command) {
		String saltCommandAsyn = BEFORE_CMD_STR + command + AFTER_CMD_ASYN + AFTER_CMD_JSON;
		String osName = System.getProperty("os.name").toLowerCase();
		String dir = null;
		if (osName.contains("windows")) {
			System.out.println("运行在 Windows 平台");
			dir = "D:\\";
		} else {
			dir = "/tmp";
		}
		try {
			CmdResult cmdResult = BashUtils.execCommand(saltCommandAsyn, dir);
			if (cmdResult.isSuccess() && StringUtils.isNotEmpty(cmdResult.get(CmdResult.MSG_TAG).toString())) {
				String job_id = cmdResult.get(CmdResult.MSG_TAG).toString();
				if (isGetRightJobId(job_id)) {
					job_id = getJobId(job_id);
					if (StringUtils.isNotEmpty(job_id)) {
						String saltCommandGetResult = BEFORE_CMD_STR
								+ StringUtils.format("sudo salt-run jobs.lookup_jid {}", StringUtils.trim(job_id))
								+ AFTER_CMD_JSON;
						System.out.println(saltCommandGetResult);
						cmdResult = BashUtils.execCommand(saltCommandGetResult, dir);
						if (cmdResult != null && cmdResult.isSuccess()) {
							return cmdResult.getResult();
						}
					}
				}
			}
		} catch (IOException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @param command
	 * @param keys
	 * @return
	 */
	public static Object execCommand(String command, String keys) {
		String result = execCommand(command);
		if (StringUtils.isNotEmpty(result)) {
			return getKeyValue(result, keys);
		}
		return null;
	}

	/**
	 * 判断是否正确返回job id
	 * 
	 * @param args
	 */
	private static Boolean isGetRightJobId(String result) {
		if (StringUtils.containsAny(result, "Executed command with job ID")) {
			return true;
		}
		return false;
	}

	private static String getJobId(String result) {
		String pattern = "\\d+"; // 匹配一个或多个数字
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(result);
		while (m.find()) {
			System.out.println("getJobId: " + m.group());
			return m.group();
		}
		return null;
	}

	public static Map<String, String> getDockerInfo(String str) {
		Map<String, String> result = new HashMap<>();
		str = str.strip().toString();
		String pattern = "port:(\\d+)\\n(\\w+)$"; // 匹配一个或多个数字
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(str);
		while (m.find()) {
			System.out.println("port: " + m.group(1));
			result.put("port", m.group(1));
			System.out.println("container id: " + m.group(2));
			result.put("containerId", m.group(2));
		}
		return result;
	}

	/**
	 * 获取json对象的key-value值
	 * 
	 * @param result
	 * @param key
	 * @return
	 */
	public static Object getKeyValue(String result, String keys) {
		if (StringUtils.isNotEmpty(result)) {
			JSONObject paramsObj = JSONObject.parseObject(result);
			if (paramsObj != null && StringUtils.isNotEmpty(keys)) {
				String[] keyS = keys.split("#");
				List<String> keyList = new ArrayList<>(keyS.length);
				for (String s : keyS) {
					if (StringUtils.isBlank(s)) {
						continue;
					}
					keyList.add(s);
				}
				keyS = new String[keyList.size()];
				keyS = keyList.toArray(keyS);
				int num = 1;
				for (String key : keyS) {
					if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(key)
							&& StringUtils.isNotEmpty(paramsObj.getString(key))) {
						Object object = paramsObj.getOrDefault((Object) key, "");
						if (num == keyList.size()) {
							return object;
						} else if (object instanceof JSONObject) {
							paramsObj = (JSONObject) object;
							num++;
						} else {
							return null;
						}
					} else {
						return null;
					}
				}
			}
			return null;
		}
		return null;
	}

	public static String getRealIp(Object ips) {
		if (ips != null) {
			if (ips instanceof JSONArray) {
				JSONArray oo = (JSONArray) ips;
				for (final Object element : oo) {
					if(element.toString().startsWith("192.168")) {
						return element.toString();
					}
				}
			} else if (ips instanceof Collection) {
				Collection<Object> oo = (Collection<Object>) ips;
				for (Object element : oo) {
					if(element.toString().startsWith("192.168")) {
						return element.toString();
					}
				}
			} else if (ips instanceof String && ips.toString().startsWith("192.168")) {
						return ips.toString();
			}
		}
		return "";

	}

	public static void main(String[] args) {
		// CmdResult cmdResult = DeviceTaskFn.execCommand("salt \"*\" grains.items");
//		Object cmdResult = SaltFn.execCommand("sudo salt \"*\" grains.items", "ddm#hwaddr_interfaces");
//		System.out.println(cmdResult.toString());
		String info = " \"ddm\": \"port:2223\\n2279e6ea045060588e828ddbb5e2da249e49b156e75f534a87cfa0ea69c348b2\"";
		info = "userId:tszx_2\\nport:2222\\nd9e366c72ebdf666c83c5a4417a649645f360d013ceb23bab350b7455e2527fc";
		getDockerInfo(info);
	}
}
